package de.g18.scavengerhunt.types;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;

import de.g18.scavengerhunt.AppApplicationContext;
import de.g18.scavengerhunt.R;
import de.g18.scavengerhunt.utils.ImageUtils;
import de.g18.scavengerhunt.utils.WebserviceUtil;

/**
 * This adapter is needed to display the profile view activity correctly 
 */
public class ProfileViewAdapter extends ArrayAdapter<String> {
	private final Context context;
	private final String[] values;
	private WebserviceUtil webserviceUtil = null;
	private Map<Integer, User> allUsers = null;

	public ProfileViewAdapter(Context context, String[] values) {
		super(context, R.layout.profiles_item, values);
		this.context = context;
		this.values = values;
		webserviceUtil = WebserviceUtil.getInstance();
		webserviceUtil.setContext(context);

		int ownUserId = AppApplicationContext.getUser().getId();
		allUsers = new HashMap<Integer, User>();

		List<User> usersInSession = webserviceUtil.getActiveUsers(AppApplicationContext.getSession().getId());
		for (User currentUser : usersInSession) {
			if (currentUser.getId() != ownUserId) {
				allUsers.put(currentUser.getId(), currentUser);
			}
		}
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View rowView = inflater.inflate(R.layout.profiles_item, parent, false);
		TextView textViewUsername = (TextView) rowView.findViewById(R.id.lblOtherUsernamesInProfile);
		TextView textViewPosition = (TextView) rowView.findViewById(R.id.lblCurrentPosition);
		ImageView imageView = (ImageView) rowView.findViewById(R.id.imgProfilePicture);

		User currentUser = allUsers.get(Integer.valueOf(values[position]));
		textViewUsername.setText(currentUser.getName());

		GeoPoint curPosition = currentUser.getCurrentGeoPoint();
		textViewPosition.setText("Lat: " + curPosition.getLatitudeE6() + ", Lng: " + curPosition.getLongitudeE6());

		Bitmap receivedProfileImage = ImageUtils.getBitmapFromBase64(webserviceUtil.receiveEncodedProfileImage(currentUser.getId()));
		imageView.setImageBitmap(ImageUtils.getResizedBitmap(receivedProfileImage, 100, 100));

		return rowView;
	}
}